<?php
//Подключаем библиотеку для рассчета статических скидок 
require_once(t3lib_extMgm::extPath('user_farm_commerce').'lib/class.farmStaticDiscounts.php');

class tx_discountsTCEhooks {
    
    
    function processDatamap_preProcessFieldArray(&$incommingFieldArray, $table, $id, &$pObj) {
		if ($table = 'user_farm_commerce_discounts') {
			switch ($incommingFieldArray['discount_type']) {
				case 1:
					$incommingFieldArray['categories'] = $this->preprocessDiscountCategories($incommingFieldArray['categories']);
					$incommingFieldArray['products'] = '';
					$incommingFieldArray['manufacturers'] = '';
					break;
				case 2:
					$incommingFieldArray['products'] = $this->preprocessDiscountProducts($incommingFieldArray['products']);
					$incommingFieldArray['categories'] = '';
					$incommingFieldArray['manufacturers'] = '';
					break;
				case 3:
					$incommingFieldArray['manufacturers'] = $this->preprocessDiscountManufacturers($incommingFieldArray['manufacturers']);
					$incommingFieldArray['categories'] = '';
					$incommingFieldArray['products'] = '';
					break;
			}
		}
    }
	
	function processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, &$pObj) {
	}

    
    function processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, &$pObj) {
        if ($table == 'user_farm_commerce_discounts') {
			if (!is_numeric($id)) $id = $pObj->substNEWwithIDs[$id];
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
				'*',
				'user_farm_commerce_discounts',
				'uid = '.intval($id)
			);
			if (!$GLOBALS['TYPO3_DB']->sql_error()) {
				$discount = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
				
				switch($discount['discount_type']) {
					case 1:
						$this->addDicountCategoriesMM($status, $discount, $pObj);
                        break;
					case 2:
						$this->addDiscountProductsMM($status, $discount, $pObj);
						break;
                    case 3:
                        $this->addDiscountManufacterersMM($status, $discount, $pObj);
                        break;
				}
                
                FarmStaticDiscounts::calculateStaticDiscount($discount);
			}
        }
    }
    
	function addDicountCategoriesMM($status, $discount, &$pObj) {
		$selectedCategories = t3lib_div::intExplode(',', $discount['categories']);
		if ($status == 'update') {
			$GLOBALS['TYPO3_DB']->exec_DELETEquery(
				'user_farm_commerce_products_discounts_mm',
				'user_farm_commerce_products_discounts_mm.uid_foreign = '.$discount['uid']
			);
			$GLOBALS['TYPO3_DB']->exec_DELETEquery(
				'user_farm_commerce_manufacturers_discount_mm',
				'user_farm_commerce_manufacturers_discount_mm.uid_foreign = '.$discount['uid']
			);
			$GLOBALS['TYPO3_DB']->exec_DELETEquery(
				'user_farm_commerce_categories_discounts_mm',
				'user_farm_commerce_categories_discounts_mm.uid_foreign = '.$discount['uid'].'
				 AND user_farm_commerce_categories_discounts_mm.uid_local NOT IN ('.implode(', ', $selectedCategories).')'
			);
			
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
				'user_farm_commerce_categories_discounts_mm.uid_local',
				'user_farm_commerce_categories_discounts_mm',
				'user_farm_commerce_categories_discounts_mm.uid_foreign = '.$discount['uid']
			);
			if (!$GLOBALS['TYPO3_DB']->sql_error()) {
				$existedMMRecords = array();
				while(list($curCategory) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res)) $existedMMRecords[] = $curCategory;
				$selectedCategories = array_diff($selectedCategories, $existedMMRecords);
			}
		}
		
		if (count($selectedCategories) > 0) {
			$queryData = array();
			foreach($selectedCategories as $category) {
				$queryData[] = '('.
					implode(',', $GLOBALS['TYPO3_DB']->fullQuoteArray(array($category, $discount['uid']), 'user_farm_commerce_categories_discounts_mm')).
					')';
			}
				
			$GLOBALS['TYPO3_DB']->sql_query('
				INSERT INTO user_farm_commerce_categories_discounts_mm (uid_local, uid_foreign)
				VALUES '.implode(', ', $queryData)
			);
		}
	}
    
    public function addDiscountManufacterersMM($status, $discount, $pObj) {
        $selectedManufacturers = t3lib_div::intExplode(',', $discount['manufacturers']);
        if ($status == 'update') {
            $GLOBALS['TYPO3_DB']->exec_DELETEquery(
                'user_farm_commerce_categories_discounts_mm',
                'user_farm_commerce_categories_discounts_mm.uid_foreign = '.$discount['uid']
            );
            $GLOBALS['TYPO3_DB']->exec_DELETEquery(
                'user_farm_commerce_products_discounts_mm',
                'user_farm_commerce_products_discounts_mm.uid_foreign = '.$discount['uid']
            );
            $GLOBALS['TYPO3_DB']->exec_DELETEquery(
                'user_farm_commerce_manufacturers_discount_mm',
                'user_farm_commerce_manufacturers_discount_mm.uid_foreign = '.$discount['uid'].'
                 AND user_farm_commerce_manufacturers_discount_mm.uid_local NOT IN ('.implode(', ', $selectedManufacturers).')'
            );
            
            $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
                'user_farm_commerce_manufacturers_discount_mm.uid_local',
                'user_farm_commerce_manufacturers_discount_mm',
                'user_farm_commerce_manufacturers_discount_mm.uid_foreign = '.$discount['uid']
            );
            if(!$GLOBALS['TYPO3_DB']->sql_error()) {
                $existedMMRecords = array();
                while(list($curManufacturer) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res)) $existedMMRecords[] = $curManufacturer;
                $selectedManufacturers = array_diff($selectedManufacturers, $existedMMRecords);
            }
        }
        if(count($selectedManufacturers) > 0) {
            $queryData = array();
            foreach($selectedManufacturers as $manufacturer) {
                $queryData[] = '('.
                    implode(', ', $GLOBALS['TYPO3_DB']->fullQuoteArray(array($manufacturer, $discount['uid']), 'user_farm_commerce_manufacturers_discount_mm')).
                    ')';
            }
            $GLOBALS['TYPO3_DB']->sql_query('
                INSERT INTO user_farm_commerce_manufacturers_discount_mm (uid_local, uid_foreign)
				VALUES '.implode(', ', $queryData)
            );
        }
    }
    
	/**
	 * Добавляет записи в таблицу связей c товарами
	 * @param string $status Record status
	 * @param array $discount Discount record
	 * @param t3lib_TCEmain $pObj TCE object
	 * 
	 * @return void
	 **/
    function addDiscountProductsMM($status, $discount, &$pObj) {
        $selectedProducts = t3lib_div::intExplode(',', $discount['products']);
		if ($status = 'update') {
			$GLOBALS['TYPO3_DB']->exec_DELETEquery(
				'user_farm_commerce_manufacturers_discount_mm',
				'user_farm_commerce_manufacturers_discount_mm.uid_foreign = '.$discount['uid']
			);
			$GLOBALS['TYPO3_DB']->exec_DELETEquery(
				'user_farm_commerce_categories_discounts_mm',
				'user_farm_commerce_categories_discounts_mm.uid_foreign = '.$discount['uid']
			);
			$GLOBALS['TYPO3_DB']->exec_DELETEquery(
				'user_farm_commerce_products_discounts_mm',
				'user_farm_commerce_products_discounts_mm.uid_foreign = '.$discount['uid'].'
				 AND user_farm_commerce_products_discounts_mm.uid_local NOT IN ('.implode(', ', $selectedProducts).')'
			);
			
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
				'user_farm_commerce_products_discounts_mm.uid_local',
				'user_farm_commerce_products_discounts_mm',
				'user_farm_commerce_products_discounts_mm.uid_foreign = '.$discount['uid']
			);
			if (!$GLOBALS['TYPO3_DB']->sql_error()) {
				$existedMMRecords = array();
				while(list($curProduct) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res)) $existedMMRecords[] = $curProduct;
				$selectedProducts = array_diff($selectedProducts, $existedMMRecords);
			}
		}
		
		if (count($selectedProducts) > 0) {
			$queryData = array();
			foreach($selectedProducts as $product) {
				$queryData[] = '('.
					implode(',', $GLOBALS['TYPO3_DB']->fullQuoteArray(array($product, $discount['uid']), 'user_farm_commerce_products_discounts_mm')).
					')';
			}
				
			$GLOBALS['TYPO3_DB']->sql_query('
				INSERT INTO user_farm_commerce_products_discounts_mm (uid_local, uid_foreign)
				VALUES '.implode(', ', $queryData)
			);
		}
    }
	
	function preprocessDiscountProducts($products) {
		$selectedProducts = t3lib_div::intExplode(',', $products);
		if (count($selectedProducts) > 0) {
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
				'tx_commerce_products.uid',
				'tx_commerce_products',
				'tx_commerce_products.uid IN ('.implode(', ', $selectedProducts).') '.
				 t3lib_BEfunc::deleteClause('tx_commerce_products')
			);
			if (!$GLOBALS['TYPO3_DB']->sql_error()) {
				if (count($selectedProducts) != $GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
					$selectedProducts = array();
					while(list($curProduct) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res)) {
						$selectedProducts[] = $curProduct;
					}
				}
				return implode(',', $selectedProducts);
			}
		}
		
		return '';
	}
	
	function preprocessDiscountCategories($categories) {
		$selectedCategories = t3lib_div::intExplode(',', $categories);
		if (count($selectedCategories) > 0) {
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
				'tx_commerce_categories.uid',
				'tx_commerce_categories',
				'tx_commerce_categories.uid IN ('.implode(', ', $selectedCategories).') '.
				  t3lib_BEfunc::deleteClause('tx_commerce_categories')
			);
			
			if (!$GLOBALS['TYPO3_DB']->sql_error()) {
				if (count($selectedCategories) != $GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
					$selectedCategories = array();
					while(list($curCategory) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res)) {
						$selectedCategories[] = $curCategory;
					}
				}
				return implode(',', $selectedCategories);
			}
		}
		return '';
	}
	
	function preprocessDiscountManufacturers($manufacturers) {
		$selectedManufacturers = t3lib_div::intExplode(',', $manufacturers);
		if (count($selectedManufacturers) > 0) {
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
				'tx_commerce_manufacturer.uid',
				'tx_commerce_manufacturer',
				'tx_commerce_manufacturer.uid IN ('.implode(', ', $selectedManufacturers).') '.
				  t3lib_BEfunc::deleteClause('tx_commerce_manufacturer')
			);
			
			if (!$GLOBALS['TYPO3_DB']->sql_error()) {
				if (count($selectedManufacturers) != $GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
					$selectedManufacturers = array();
					while(list($curManufacturer) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res)) {
						$selectedManufacturers[] = $curManufacturer;
					}
				}
				return implode(',', $selectedManufacturers);
			}
		}
		return '';
	}
}
?>